package com.huatai.datacenter.service.impl;

import com.huatai.common.httputil.HttpRequest;
import com.huatai.common.httputil.ResponseSpec;
import com.huatai.datacenter.config.ServerInfo;
import com.huatai.datacenter.entity.PutSingle;
import com.huatai.datacenter.service.PutService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: ht-system
 * @description: 数据写入接口
 * @author: songxiude
 * @create: 2023-04-25 15:00
 **/
@Slf4j
@Service
public class PutServiceImpl extends BaseServiceImpl implements PutService {

	@Autowired
	private ServerInfo serverInfo;


	/**
	 * 同步写入 单个设备
	 */
	@Override
	public boolean syncPut(PutSingle putSingle) {
		String compose = composePut(putSingle);
		return syncPut(compose);
	}

	/**
	 * 异步写入 单个设备
	 */
	@Override
	public void asyncPut(PutSingle putSingle) {
		String compose = composePut(putSingle);
		asyncPut(compose);
	}

	/**
	 * 同步写入 多个设备
	 */
	@Override
	public boolean syncPutList(List<PutSingle> putSingles) {
		String compose = composePutList(putSingles);
		return syncPut(compose);
	}

	/**
	 * 异步写入 设备集合
	 */
	@Override
	public void asyncPutList(List<PutSingle> putSingles) {
		String compose = composePutList(putSingles);
		asyncPut(compose);
	}

	/**
	 * 异步写入计算差值
	 */
	@Override
	public Boolean syncPutDifference(PutSingle putSingles) {
		String compose = composePut(putSingles);
		return syncPut(compose);
	}


	/**
	 * 初始化错误数据
	 *
	 * @param composePut 保存的JSON对象
	 */
	private boolean syncPut(String composePut) {
		String result = HttpRequest.post(serverInfo.getPutUrl())
			.bodyString(composePut)
			.execute()
			.onFailed(((request, e) -> log.error("big data connection error info : " + e.getMessage())))
			.onSuccessOpt(ResponseSpec::asString).orElse("error");
		return !"error".equals(result);
	}

	/**
	 * 初始化错误数据
	 *
	 * @param composePut 保存的JSON对象
	 */
	private void asyncPut(String composePut) {
		HttpRequest.post(serverInfo.getPutUrl())
			.bodyString(composePut)
			.async()
			.onFailed(((request, e) -> log.error("big data connection error info : " + e.getMessage())))
			.onSuccessful(ResponseSpec::asJsonNode);
	}

}
